## library(redist)
library(readr)
library(maptools)
library(doMC)
source("../random_submap.R")

ben_theme <- function(){
    theme_classic() +
        theme(panel.background = element_blank(),
              panel.grid.major = element_blank(),
              panel.grid.minor = element_blank(),
              axis.line = element_line(colour = "black"),
              panel.border = element_rect(colour = "black", fill = NA, size = 1),
              strip.background = element_blank(),
              legend.position = "bottom", legend.title = element_blank(),
              plot.title = element_text(hjust = 0.5))
}

## Load map
nh <- readShapePoly("../../data/nh/nh_final.shp")

## Set parameters
params <- expand.grid(
    nprecs = seq(40, 200, by = 40),
    ndists = c(2, 5, 10),
    alg = c("enumpart"),
    nsims = 1:25,
    stringsAsFactors = FALSE
)

dir.create("../../data/runtime_test", showWarnings = FALSE)

## Get info on job
i <- as.numeric(Sys.getenv("SLURM_ARRAY_TASK_ID"))

## ---------
## Run tests
## ---------
## Get parameters
nprecs <- params$nprecs[i]
ndists <- params$ndists[i]
alg <- params$alg[i]

## Sample map
nh_sub <- random_submap(nh, nprecs)

## ## Runtime for redist.enumerate()
## if(alg == "redist"){
##     start <- Sys.time()
##     re_out <- redist.enumerate(nh_sub, ndists = ndists)
##     end <- Sys.time()
##     time <- difftime(end, start, units = "secs")
## }

## Runtime for enumpart
if(alg == "enumpart"){

    start <- Sys.time()
    
    ## Convert shp file to adjacency list
    adjlist <- poly2nb(nh_sub, queen = FALSE)

    ## Sink
    adjlist_map <- c()
    for(k in 1:length(adjlist)){
        sub <- adjlist[[k]]
        sub <- sub[sub > k]
        if(length(sub) > 0){
            for(l in 1:length(sub)){
                adjlist_map <- rbind(adjlist_map, c(k, sub[l]))
            }
        }
    }
    write_delim(
        data.frame(adjlist_map),
        path = paste0("../../data/runtime_test/adjlist_map_", i, ".dat"),
        col_names = FALSE
    )
    
    ## Order edges
    system(paste0("python ../ndscut.py <../../data/runtime_test/adjlist_map_", i, ".dat >../../data/runtime_test/adjlist_map_ordered_", i, ".dat"))

    ## Run enumpart
    system(paste0("../../enumpart_private/enumpart ../../data/runtime_test/adjlist_map_ordered_", i, ".dat -k ", ndists))

    end <- Sys.time()
    time <- difftime(end, start, units = "secs")
    
}

## Format and save
out <- data.frame(nprecs = nprecs, ndists = paste0(ndists, " Districts"),
                  alg = alg, runtime = as.numeric(time))
write_csv(out, path = paste0("../../data/runtime_test/runtime_test_", i, ".csv"))
